package com.baor.utils;

import com.baor.domain.vx.Amount;
import com.baor.domain.vx.Payer;
import lombok.Data;
import okhttp3.HttpUrl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 *  第二步：发送http请求获取prepay_id
 */

@Data
public class WeChatPayUtil {
    //一下参数转成JSON字符串
    //小程序appid
    private String appid;//公众号ID
    //商品描述
    private String description;//商品描述
    private String mchid;//直连商户号

    //回调通知地址
    private String notify_url;//通知地址
    //订单号
    private String out_trade_no;//【商户订单号】 商户系统内部订单号，只能是数字、大小写字母_-*且在同一个商户号下唯一。
    private Amount amount;//订单金额
    private Payer payer;//支付者

    public static Map<String,Object> httpRequest(String requestUrl, String requestMethod, String outputStr, Map<String,Object> params,String nonceStr,long timestamp){
        // 创建SSLContext
        StringBuffer buffer=null;
        String res = null;
        try{
            URL url = new URL(requestUrl);
            HttpUrl httpUrl = HttpUrl.parse(requestUrl);

            res = AuthorizationHeaderUtil.getSign(params.get("mchid").toString(),"POST",httpUrl,outputStr,(String)params.get("serialno"),nonceStr,timestamp);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            System.out.println("WECHATPAY2-SHA256-RSA2048 "+res);
            conn.setRequestProperty("Authorization","WECHATPAY2-SHA256-RSA2048 "+res);
            conn.setRequestProperty("Content-Type","application/json");
            conn.setRequestMethod(requestMethod);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //往服务器端写内容
            if(null != outputStr){
                OutputStream os=conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }
            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        Map<String,Object> result = new HashMap<>();
        result.put("response",buffer.toString());
        result.put("sign",res);
        return result;
    }
}
